﻿using System;
using System.Windows.Forms;
using BizTalk.BuildGenerator.MetaData;
using BizTalk.BuildGenerator.UI.Navigation;

namespace BizTalk.BuildGenerator.UI.UserControls
{
    public partial class GenerationOptionsControl : UserControl, IWizardControl
    {
        private GenerationArgs _args;

        public GenerationOptionsControl()
        {
            InitializeComponent();
        }

        private void GenerationOptionsControlLoad(object sender, EventArgs e)
        {
            if (DesignMode) return;
            foreach (var provider in Configuration.ConfigurationFacade.BuildProviders)
                BuildProviderComboBox.Items.Add(provider);

            if (_args == null || _args.GenerationProvider == null) return;
            if (BuildProviderComboBox.Items.Contains(_args.GenerationProvider))
                BuildProviderComboBox.SelectedText = _args.GenerationProvider;
        }
        /// <summary>
        /// Registers the args for use by this control
        /// </summary>
        /// <param name="args"></param>
        public void RegisterArgs(GenerationArgs args)
        {
            _args = args;
            
        }

        #region IWizardControl Members
        /// <summary>
        /// Implements move next
        /// </summary>
        /// <returns></returns>
        public MoveNextResult MoveNext()
        {
            var result = new MoveNextResult();
            if (string.IsNullOrEmpty(BuildProviderComboBox.Text))
            {
                result.CanMoveNext = false;
                result.AddError("Please select a build provider");                
                return result;
            }

            var providerType = Type.GetType(BuildProviderComboBox.SelectedText, false, true);
            if (providerType == null)
            {
                result.CanMoveNext = false;
                result.AddError("The type of the selected provider can not be found.  Please check its assembly");
                return result;
            }

            if (providerType.IsAssignableFrom(typeof(IBuildProvider)))
            {
                result.CanMoveNext = false;
                result.AddError("The type of the selected provider does not implement the correct interface");
                return result;
            }
            result.CanMoveNext = true;
            _args.GenerationProvider = BuildProviderComboBox.SelectedText;

            return result;
        }

        #endregion
    }
}
